﻿using mars_server.csharp.cache;
using mars_server.csharp.socket;
using mars_server.csharp.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using mars_server.csharp.CO;
using mars_server.csharp.AO;
using mars_server.csharp.AO.impl;
using mars_server.csharp.dao;
using mars_server.csharp.dao.impl;

namespace mars_server.csharp.myTask
{
    public class ServerTask
    {
       
        /**
         * 查询那些客户端套接字需要线程资源进行读取、业务操作
         * */
        public static void selectTask()
        {
            while (true)//无休止的轮询
            {
                for(int i = UserSocketCache.UserSocketList.Count - 1; i >= 0; i--)
                {
                    UserSocket userSocket = UserSocketCache.UserSocketList[i];
                    if (userSocket == null) continue;
                    if (!userSocket.IsOp)//该UserSocket没有操作
                    {
                        if (userSocket.client.Available > 0)
                        {
                            userSocket.IsOp = true;
                            Console.WriteLine("[info]=====当前用户数：" + UserSocketCache.UserSocketList.Count);
                            BusinessTask businessTask = BusinessTask.Instance;
                            businessTask.dealMessage(userSocket);
                            Console.WriteLine("主线程");
                        }
                    }
                }
            }
        }

        public static void HeartBeatTask()
        {
            Console.WriteLine("[info]---开启心跳检测线程------：【心跳】");
            UserSocketAO userSocketAO = UserSocketAOImpl.Instance;
            UserSocketManager userSocketManager = UserSocketManagerImpl.Instance;
            while (true)
            {
                for (int i = UserSocketCache.UserSocketList.Count - 1; i >= 0; i--)
                {
                    UserSocketCache.UserSocketList[i].HeartBeat--;
                    if (UserSocketCache.UserSocketList[i].HeartBeat == 0)
                    {
                        Console.WriteLine("[info]:--【心跳】用户：" + SocketUtil.getSocketInfo(UserSocketCache.UserSocketList[i])+"无响应退出");
                        userSocketManager.deleteUserSocketByUserSocketDO(UserSocketCache.UserSocketList[i]);
                    }
                }
                Thread.Sleep(20000);
            }
            
        }
    }
}
